package Reflect;

import java.lang.reflect.Field;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-10-15
 * Time: 15:38
 */
public class getField {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        //创建字节码文件对象
        Class<?> stuClass = Class.forName("Reflect.Student");

        //获取所有共有的属性
        Field[] fields = stuClass.getFields();
        for (Field fie:fields) {
            System.out.println(fie);
        }

        //获取某个公共属性
        Field age = stuClass.getField("age");
        System.out.println(age);

        //获取所有属性
        Field[] declaredFields = stuClass.getDeclaredFields();
        for (Field fie:declaredFields) {
            System.out.println(fie);
        }

        //获取某个属性，包括私有的成员变量
        Field name = stuClass.getDeclaredField("name");//获取指定属性
        System.out.println(name);
        Student stu1 = new Student(20);
        System.out.println(stu1);

        //临时解除权限检查
        name.setAccessible(true);

        //设置属性值
        name.set(stu1,"陈达峰");//stu1为设置的属性所属对象
        System.out.println(stu1);

    }
}
